const express = require('express');
const userModel = require('../../model/userModel');
const md5 = require('md5');
const jwt = require('jsonwebtoken');
const { SECRET } = require('../../config/config');

const router = express.Router();

//login to obtain token
router.post('/login', (req, res) => {
    let { username, password } = req.body;

    userModel.findOne({ username: username, password: md5(password) }).then(
        data => {
            // crate token
            if (!data) {

                return res.json(
                    {
                        code: 2001,
                        message: '账号或密码错误~~~',
                        data: null
                    }
                )
            }

            let token = jwt.sign({
                username: data.username,
                _id: data._id,
            },
                SECRET,
                {
                    expiresIn: 60 * 60 * 24 * 7
                });

            //return token 
            res.json({
                code: '0000',
                message: '获取token成功',
                data: token
            })
        }, () => {
            res.json({
                code: '2002',
                message: '登录错误~~~',
                data: null

            })
        }
    )

})

module.exports = router;
